<template>
    <view class="">
        <navView navTitle="订单支付" titleColor="#fff" :isBack="true"></navView>
        <view class="container">
            <!-- 订单信息 -->
            <view class="order-info">
                <view class="info-item">
                    <text class="label">订单号：</text>
                    <text class="value">{{ orderInfo.order_no }}</text>
                </view>
                <view class="info-item">
                    <text class="label">支付金额：</text>
                    <text class="amount">¥{{ orderInfo.amount }}</text>
                </view>
                <view class="info-item">
                    <text class="label">有效期至：</text>
                    <text class="value">{{ orderInfo.expire_time }}</text>
                </view>
            </view>

            <!-- 确认支付 -->
            <view class="footer">
                <button class="confirm-btn" @click="handlePayment">确认支付</button>
            </view>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            orderInfo: {
                order_no: '',
                amount: 0,
                expire_time: ''
            },
            payParams: {},
            selectedMethod: 0
        };
    },
    onLoad(options) {
        if (options.id && options.amount) {
            console.log(options,'options');
            this.getOrderDetail(options.id,options.amount)
        }
    },
    methods: {
        formatTime(timestamp) {
            const date = new Date(timestamp * 1000); // 假设是秒级时间戳
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        },
        async getOrderDetail(id, amount) {
            try {
                const formattedAmount = parseFloat(amount).toFixed(2);
                
                // // 2. 创建订单
                const createRes = await this.$request(
                    '/addons/qingdong/pays/createOrder',
                    'POST',
                    {
                        relation_id: id,
                        amount: formattedAmount,
                        remark: "支付"
                    }
                );

                console.log('创建订单响应:', createRes);

                // 3. 获取支付参数
                const payParamsRes = await this.$request(
                    '/addons/qingdong/pays/submit',
                    'POST',
                    {
                        out_trade_no: createRes.data,
                        title: '支付',
                        amount: formattedAmount,
                        paytype: 'wechat',
                        method: 'miniapp',
                    }
                );
                console.log('支付参数响应:', payParamsRes);

                // 4. 更新支付参数
                // 更新支付参数（移除自动支付）
                if (payParamsRes.data) {
                    this.payParams = payParamsRes.data;
                    this.orderInfo = {
                        order_no: createRes.data,
                        amount: formattedAmount,
                        expire_time: this.formatTime(payParamsRes.data.timeStamp)
                    }
                    uni.showToast({ title: '支付环境通过' });
                } else {
                    uni.showToast({ title: '支付环境异常', icon: 'none' });
                }

            } catch (error) {
                console.error('支付流程异常:', error);
                uni.showToast({ title: '请求失败，请重试', icon: 'none' });
            }
        },

        async handlePayment() {
            if (!this.payParams) {
                uni.showToast({ title: '支付参数未就绪', icon: 'none' });
                return;
            }
            uni.showLoading({ title: '支付中...' });
            try {
                uni.requestPayment({
                    appId: this.payParams.appId,
                    nonceStr: this.payParams.nonceStr,
                    package: this.payParams.package,
                    paySign: this.payParams.paySign,
                    signType: this.payParams.signType,
                    timeStamp: this.payParams.timeStamp,
                    success: (e) => {
                        uni.hideLoading();
                        uni.showToast({ title: '支付成功' });
                        setTimeout(() => uni.navigateBack(), 1500);
                    },
                    fail: (e) => {
                        uni.showModal({
                            content: "支付失败,原因为: " + e.errMsg,
                            showCancel: false
                        })
                    }
                })
            } catch (err) {
                uni.hideLoading();
                console.error('支付失败:', err);
                uni.showToast({
                    title: err.errMsg || '支付失败',
                    icon: 'none'
                });
            }
        }
    }
};
</script>

<style lang="scss">
.container {
    padding: 20rpx;

    .order-info {
        background: #fff;
        border-radius: 16rpx;
        padding: 30rpx;
        margin-bottom: 20rpx;

        .info-item {
            display: flex;
            align-items: center;
            margin-bottom: 20rpx;
            font-size: 28rpx;

            .label {
                color: #666;
                width: 160rpx;
            }

            .amount {
                color: #ff4500;
                font-size: 36rpx;
                font-weight: bold;
            }
        }
    }

    .payment-methods {
        background: #fff;
        border-radius: 16rpx;
        padding: 30rpx;

        .title {
            font-size: 32rpx;
            font-weight: bold;
            margin-bottom: 30rpx;
        }

        .method-item {
            display: flex;
            align-items: center;
            padding: 20rpx 0;
            border-bottom: 1rpx solid #eee;

            .method-icon {
                width: 60rpx;
                height: 60rpx;
                margin-right: 20rpx;
            }

            .method-name {
                flex: 1;
                font-size: 28rpx;
            }
        }
    }

    .footer {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        padding: 20rpx;
        background: #fff;

        .confirm-btn {
            background: #2979ff;
            color: #fff;
            border-radius: 50rpx;
            height: 80rpx;
            line-height: 80rpx;
            font-size: 32rpx;
        }
    }
}
</style>